<template>
  <Upload :action="action" :headers="getHeader" :accept="accept" :file-list="fileList" :data="uploadPayload"
    list-type="picture-card" :max-count="maxFileCount" :before-upload="beforeUpload" @success="onSuccess"
    @remove="onRemove" @preview="onPreview">
    <template #default>
      <span v-if="fileList.length < maxFileCount">+ 上传</span>
    </template>
  </Upload>
</template>

<script setup lang="ts">
import { ref, onMounted, watchEffect } from "vue";
import { Upload, message } from "ant-design-vue";
import { API_BASE_URL } from "@/modules/base-request/src/request/config";
import { post } from "@/modules/base-request/src/request";
import { Form } from 'ant-design-vue';
const props = defineProps({
  action: { type: String, required: true }, // 上传地址
  accept: { type: String, default: "" }, // 可接受的文件类型
  maxFileCount: { type: Number, default: 5 }, // 最大上传文件数量
  customValidator: { type: Function, default: null }, // 自定义文件校验函数
  getFileGroupById: { type: Function }, // 根据 groupId 获取文件列表
  value: { type: String, default: null }, // 绑定的 groupId
  delUrl: { type: String, default: "" }
});
const formItemContext = Form.useInjectFormItemContext();
const emit = defineEmits(["update:value"]);

// 文件列表和 groupId 状态
const fileList = ref<any[]>([]);
const groupId = ref<string | null>(props.value);
const action = `${API_BASE_URL}${props.action}`
// 动态计算上传 payload
const uploadPayload = (file: any) => {
  return {
    uploadFile: file,
    data: JSON.stringify({
      groupId: groupId.value || "", // 动态绑定 groupId
    })
  };
};
const getHeader = {
  authorization: `Bearer ${localStorage.getItem("token")}`
}

// 监听外部传入的 value（groupId）

// watch(
//   () => props.value,
//   (newValue) => {
//     groupId.value = newValue;
//     loadFileGroup(); // 根据新的 groupId 加载文件
//   },

// );

// 初始化时加载已有文件组
const loadFileGroup = async () => {
  if (groupId.value && props.getFileGroupById) {
    const files = await props.getFileGroupById(groupId.value);
    fileList.value = files.map((file: any) => ({
      uid: file.id,
      name: file.name,
      status: "done",
      url: file.url,
      id: file.id,
    }));
  }
};
watchEffect(() => {
  groupId.value = props.value;
  loadFileGroup();
})
// 文件上传前校验
const beforeUpload = (file: File) => {
  if (props.customValidator) {
    const result = props.customValidator(file);
    if (typeof result === "string") {
      message.error(result);
      return false;
    }
    if (!result) return false;
  }
  return true;
};

// 文件上传成功回调
const onSuccess = (response: any, file: any) => {
  if (!groupId.value && response.data.groupId) {
    groupId.value = response.data.groupId; // 接收新的 groupId
    emit("update:value", groupId.value); // 通知表单更新 groupId
    formItemContext.onFieldChange()
  }
  file.uid = response.data.id;
  file.id = response.data.id;
  file.url = response.data.url;
  fileList.value.push(file);
};

// 文件移除
const onRemove = async (file: any) => {
  // 删除文件 
  const f = await post<{
    data: null,
    errorMsg: string
  }>(props.delUrl, {
    groupId: groupId.value,
    id: file.id
  })
  if (!!f.data) {
    fileList.value = fileList.value.filter((f) => f.uid !== file.uid);
    if (!fileList.value.length) {
      emit("update:value", undefined)
      formItemContext.onFieldChange()

    }
  } else {
    message.error(f.errorMsg)
  }
};

// 文件预览
const onPreview = (file: any) => {
  if (file.url) {
    window.open(file.url, "_blank");
  } else {
    message.info("无法预览此文件");
  }
};

onMounted(loadFileGroup);
</script>

<style scoped></style>
